package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"post/cache"
	"post/model"
	"strconv"
	"time"
)

func Add(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	if title == "" || content == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
	}
	data := model.Article{
		//Model:   gorm.Model{},
		Title:   title,
		Content: content,
	}
	err := model.DB.Debug().Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "发布失败",
		})
	}
	var article model.Article
	redis_key := "article_" + strconv.Itoa(int(data.ID))
	model.DB.Where("id=?", data.ID).Find(&article)
	marshal, _ := json.Marshal(&article)
	cache.Rdb.Set(cache.Ctx, redis_key, marshal, time.Hour*2)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "发表成功",
	})
}
func Del(c *gin.Context) {
	id := c.Query("id")
	var article model.Article
	err := model.DB.Where("id = ?", id).Delete(&article).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "删除失败",
		})
		return
	}
	redis_key := "article_" + id
	cache.Rdb.Del(cache.Ctx, redis_key)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
}
func List(c *gin.Context) {
	var articles []model.Article
	err := model.DB.Debug().Find(&articles).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}

	redis_key := "list"
	marshal, _ := json.Marshal(&articles)
	cache.Rdb.Set(cache.Ctx, redis_key, marshal, time.Hour*2)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": articles,
	})
	return
}
